package cn.tedu.store.admin.webapi.service.impl;


import cn.tedu.store.admin.webapi.mapper.RoleMapper;
import cn.tedu.store.commons.ex.ServiceException;
import cn.tedu.store.commons.pojo.admin.dto.RoleAddNewDTO;
import cn.tedu.store.commons.pojo.admin.entity.Role;
import cn.tedu.store.commons.pojo.admin.vo.RoleListItemVO;
import cn.tedu.store.commons.pojo.admin.vo.RoleStandardVO;
import cn.tedu.store.commons.web.ServiceCode;
import cn.tedu.store.admin.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    RoleMapper roleMapper;

    @Override
    public void addNew(RoleAddNewDTO roleAddNewDTO) {
        int count = roleMapper.countByName(roleAddNewDTO.getName());
        if (count != 0) {
            String message = "添加角色失败,该角色已存在!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        Role role = new Role();
        BeanUtils.copyProperties(roleAddNewDTO, role);
        roleMapper.insert(role);
        log.debug("添加管理员成功!");
    }

    @Override
    public void delete(Long id) {
        int count = roleMapper.countById(id);
        if (count == 0) {
            String message = "删除角色失败,该角色不存在!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        roleMapper.deleteById(id);
        log.debug("删除角色成功!");
    }

    @Override
    public void updateById(Long id, RoleAddNewDTO roleAddNewDTO) {
        log.debug("即将处理修改角色业务!");
        RoleStandardVO roleStandardVO = roleMapper.getStandardById(id);
        if (roleStandardVO == null) {
            String message = "修改角色失败,该角色不存在!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        Role role = new Role();
        BeanUtils.copyProperties(roleAddNewDTO, role);
        role.setId(id);
        log.debug("即将修改的数据: {}", role);
        int count = roleMapper.updateById(role);
        if (count != 1){
            String message = "修改角色失败,服务器忙,请稍后重试!";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }

    }

    @Override
    public List<RoleListItemVO> list() {
        log.debug("开始处理查询角色列表业务!");
        return roleMapper.list();
    }
}
